﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Text;
using Business;
using System.Data;
using System.Web.Security;
public partial class admin_MachineStatus : @base {
    DataTable components = new DataTable();
    ReportServices rs = new ReportServices();
    DataSheetService ds = new DataSheetService();
    Encryption objenc = new Encryption();
    ImageEditor objimg = new ImageEditor();
    
 UserServices user = new UserServices();
    ReportServices report = new ReportServices();
    //int selectedClient_id;
    public int workorderID = 0;
    // mshtml.HTMLWindow2Class window;
    protected void Page_Load(object sender, EventArgs e)
    {


        if (UserDetails == null)
        {
            //string message = "User has been logged out!";
           // Server.Transfer("ErrorMessage.aspx?message=" + message);
            Server.Transfer("../Default.aspx");
        }
        string currDate = Request.QueryString["date"];
        if (!IsPostBack)
        {
            String machineID = Request.QueryString["machine_id"];
            BindComponentStatus(machineID);
            setDateList(ToInt(machineID));
            DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(currDate));
       

        }
        
        // int t = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(currDate));
          
    }
    protected void DropDownList_IndexChanged(Object sender , EventArgs e)
    {
        string date = DropDownList1.SelectedValue.ToString();
        Server.Transfer( "MachineStatus.aspx?machine_id=" + MACHINEID + "&date=" + date);
        
    }
    protected void BindComponentStatus(String machineID)
    {
        CreateConn objcon = new CreateConn();
       /* try
        {
            string query = "SELECT siteName, machineName, photo" +
                    " FROM  Sites INNER JOIN" +
                    " Machines ON Sites.site_id = Machines.site_id" +
                    " WHERE (Machines.machine_id = " + machineID + ")";
            DataTable dt = objcon.SQLConnDataTable(query);

            sitename.Text = dt.Rows[0]["siteName"].ToString();
            machinename.Text = dt.Rows[0]["machineName"].ToString();

            //setting the Machine Image
            string path = Server.MapPath("../photos/" + dt.Rows[0]["photo"].ToString());
            System.Drawing.Image image = System.Drawing.Image.FromFile(path, true);
            ImageEditor objimg = new ImageEditor();
            int height = 0;
            int width = 0;
            if (objimg.isPortrait(image))
            {
                height = 160;
                width = 120;
            }
            else
            {
                height = 120;
                width = 160;
            }
            // machinePhoto.Attributes.Add("Width", Convert.ToString(width));
            // machinePhoto.Attributes.Add("Height", Convert.ToString(height));
            // machinePhoto.ImageUrl = "../photos/" + dt.Rows[0]["photo"].ToString();
            ImageButton1.Attributes.Add("Width", Convert.ToString(width));
            photoHyperLink.Attributes.Add("href", "../photos/" + dt.Rows[0]["photo"].ToString());
            ImageButton1.Attributes.Add("Height", Convert.ToString(height));
            ImageButton1.ImageUrl = "../photos/" + dt.Rows[0]["photo"].ToString();

            if (dt.Rows[0]["photo"].ToString() == "NotAvailable.jpg")
            {
                photoHyperLink.Visible = false;
            }
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }*/
        try
        {
            string queryDate = String.Empty;
            string currDate = String.Empty;
            DataTable date_dt = new DataTable();
            DataTable prev_dt = new DataTable();

            string date = Request.QueryString["date"];
            if (date == null)
            {
                objcon = new CreateConn();
                queryDate = "SELECT TOP (1) dateRecorded" +
                    " FROM (SELECT DISTINCT TOP (1) ComponentStatus.dateRecorded" +
                            " FROM Components INNER JOIN" +
                            " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                            " WHERE   (Components.machine_id = '" + machineID + "')" +
                            " ORDER BY ComponentStatus.dateRecorded DESC) AS data" +
                    " ORDER BY dateRecorded";
                date_dt = objcon.SQLConnDataTable(queryDate);
                currDate = date_dt.Rows[0]["dateRecorded"].ToString();
            }
            else
            {
                currDate = date;
            }
            //for current component status
            objcon = new CreateConn();
            /*    string component_query = "SELECT Components.componentName, ComponentStatus.status_id, ComponentStatus.comments, StandardComments.commentDescription" +
                    " FROM Components INNER JOIN" +
                    " ComponentStatus ON Components.component_id = ComponentStatus.component_id INNER JOIN" +
                    " StandardComments ON ComponentStatus.comment_id = StandardComments.comment_id" +
                    " WHERE (Components.machine_id = '" + machineID + "') AND (ComponentStatus.dateEntered = CONVERT(datetime, '" + currDate + "', 103))";
              */
            string component_query = "SELECT Components.componentName, ComponentStatus.status_id, ComponentStatus.comments" +
                                   " FROM            Components INNER JOIN" +
                                   " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                                   " WHERE        (Components.machine_id =" + machineID + ") AND (ComponentStatus.dateRecorded = CONVERT(datetime, '" + currDate + "', 103))";
            DataTable component_dt = objcon.SQLConnDataTable(component_query);

            //for previous component status
            string prevDate = GetPreviousDate(machineID, currDate);
            objcon = new CreateConn();
            string prevcomponent_query = "SELECT ComponentStatus.status_id" +
                " FROM Components INNER JOIN" +
                " ComponentStatus ON Components.component_id = ComponentStatus.component_id " +
                " WHERE (Components.machine_id = '" + machineID + "') AND (ComponentStatus.dateRecorded = CONVERT(datetime, '" + prevDate + "', 103))";
            DataTable prevcomponent_dt = objcon.SQLConnDataTable(prevcomponent_query);
         /*   System.Web.UI.WebControls.ListItem index = DropDownListDate.Items.FindByValue(currDate);
            DropDownListDate.SelectedIndex = DropDownListDate.Items.IndexOf(index);
           */
            string currCol = "#666666";
            string prevCol = "#666666";
            ComponentName1.Text = component_dt.Rows[0]["componentName"].ToString();
            currCol = ConvertToColor(component_dt.Rows[0]["status_id"].ToString());
            string befDate = GetBeforeDate(machineID, currDate);
            CurrentLabel1.NavigateUrl = "MachineStatus.aspx?machine_id=" + machineID + "&date=" + befDate;
            if (currDate != prevDate)
            {
                prevCol = ConvertToColor(prevcomponent_dt.Rows[0]["status_id"].ToString());
                PreviousLabel1.NavigateUrl = "MachineStatus.aspx?machine_id=" + machineID + "&date=" + prevDate;
            }
            CurrentLabel1.ForeColor = System.Drawing.Color.FromName(currCol);
            Description1.BackColor = System.Drawing.Color.FromName(currCol);
            PreviousLabel1.ForeColor = System.Drawing.Color.FromName(prevCol);
            Description1.Text = component_dt.Rows[0]["comments"].ToString();
            if (ComponentName1.Text != null)
            {
                Component1.Visible = true;
            }
            if (ComponentName1.Text.ToString().EndsWith("box"))
            {
                HyperLink1Oil.NavigateUrl = "oilreport.aspx";
                HyperLink1Oil.Visible = true;
            }
            ComponentName2.Text = component_dt.Rows[1]["componentName"].ToString();
            currCol = ConvertToColor(component_dt.Rows[1]["status_id"].ToString());
            CurrentLabel2.NavigateUrl = "MachineStatus.aspx?machine_id=" + machineID + "&date=" + befDate;
            if (currDate != prevDate)
            {
                prevCol = ConvertToColor(prevcomponent_dt.Rows[1]["status_id"].ToString());
                PreviousLabel2.NavigateUrl = "MachineStatus.aspx?machine_id=" + machineID + "&date=" + prevDate;
            }
            CurrentLabel2.ForeColor = System.Drawing.Color.FromName(currCol);
            Description2.BackColor = System.Drawing.Color.FromName(currCol);
            PreviousLabel2.ForeColor = System.Drawing.Color.FromName(prevCol);
            Description2.Text = component_dt.Rows[1]["comments"].ToString();
            if (ComponentName2.Text != null)
            {
                Component2.Visible = true;
            }
            if (ComponentName2.Text.ToString().EndsWith("box"))
            {
                HyperLink2Oil.NavigateUrl = "oilreport.aspx";
                HyperLink2Oil.Visible = true;
            }
            ComponentName3.Text = component_dt.Rows[2]["componentName"].ToString();
            currCol = ConvertToColor(component_dt.Rows[2]["status_id"].ToString());
            CurrentLabel3.NavigateUrl = "MachineStatus.aspx?machine_id=" + machineID + "&date=" + befDate;
            if (currDate != prevDate)
            {
                prevCol = ConvertToColor(prevcomponent_dt.Rows[2]["status_id"].ToString());
                PreviousLabel3.NavigateUrl = "MachineStatus.aspx?machine_id=" + machineID + "&date=" + prevDate;
            }
            CurrentLabel3.ForeColor = System.Drawing.Color.FromName(currCol);
            Description3.BackColor = System.Drawing.Color.FromName(currCol);
            PreviousLabel3.ForeColor = System.Drawing.Color.FromName(prevCol);
            Description3.Text = component_dt.Rows[2]["comments"].ToString();
            if (ComponentName3.Text != null)
            {
                Component3.Visible = true;
            }
            if (ComponentName3.Text.ToString().EndsWith("box"))
            {
                HyperLink3Oil.NavigateUrl = "oilreport.aspx";
                HyperLink3Oil.Visible = true;
            }
            ComponentName4.Text = component_dt.Rows[3]["componentName"].ToString();
            currCol = ConvertToColor(component_dt.Rows[3]["status_id"].ToString());
            CurrentLabel4.NavigateUrl = "MachineStatus.aspx?machine_id=" + machineID + "&date=" + befDate;
            if (currDate != prevDate)
            {
                prevCol = ConvertToColor(prevcomponent_dt.Rows[3]["status_id"].ToString());
                PreviousLabel4.NavigateUrl = "MachineStatus.aspx?machine_id=" + machineID + "&date=" + prevDate;
            }
            CurrentLabel4.ForeColor = System.Drawing.Color.FromName(currCol);
            Description4.BackColor = System.Drawing.Color.FromName(currCol);
            PreviousLabel4.ForeColor = System.Drawing.Color.FromName(prevCol);
            Description4.Text = component_dt.Rows[3]["comments"].ToString();
            if (ComponentName4.Text != null)
            {
                Component4.Visible = true;
            }
            if (ComponentName4.Text.ToString().EndsWith("box"))
            {
                HyperLink4Oil.NavigateUrl = "oilreport.aspx";
                HyperLink4Oil.Visible = true;
            }
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
    }

    protected string GetPreviousDate(string machineID, string date)
    {
        CreateConn objcon = new CreateConn();
        try
        {
            DateTime currdate = Convert.ToDateTime(date);
            string queryPrevDate = "SELECT DISTINCT ComponentStatus.dateRecorded" +
                " FROM Components INNER JOIN" +
                " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                " WHERE (Components.machine_id = " + machineID + ")" +
                " ORDER BY ComponentStatus.dateRecorded DESC";
            DataTable prev_dt = objcon.SQLConnDataTable(queryPrevDate);
            foreach (DataRow dr in prev_dt.Rows)
            {
                string thisdate = dr["dateRecorded"].ToString();
                DateTime prevdate = Convert.ToDateTime(thisdate);
                if (prevdate < currdate)
                {
                    date = thisdate;
                    break;
                }
            }
            //date = prev_dt.Rows[0]["dateEntered"].ToString();
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        return date;
    }

    protected string GetBeforeDate(string machineID, string date)
    {
        //Thao's code
        CreateConn objcon = new CreateConn();
        try
        {
            DateTime currdate = Convert.ToDateTime(date);
            string queryBefDate = "SELECT DISTINCT ComponentStatus.dateRecorded" +
                " FROM Components INNER JOIN" +
                " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                " WHERE (Components.machine_id = " + machineID + ")" +
                " ORDER BY ComponentStatus.dateRecorded ";
            DataTable bef_dt = objcon.SQLConnDataTable(queryBefDate);
            foreach (DataRow dr in bef_dt.Rows)
            {
                string thisdate = dr["dateRecorded"].ToString();
                DateTime befdate = Convert.ToDateTime(thisdate);
                if (befdate > currdate)
                {
                    date = thisdate;
                    break;
                }
            }
            //date = prev_dt.Rows[0]["dateEntered"].ToString();
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        return date;
    }

    protected string ConvertToColor(string col)
    {
        if (col == "2")
        {
            col = "#FFFF00";
        }
        else if (col == "3")
        {
            col = "#FF9900";
        }
        else if (col == "4")
        {
            col = "#FF0000";
        }
        else
        {
            col = "#00FF00";
        }
        return col;
    }
    protected void setDateList(int machine_id)
    {
        DataTable Dates = new DataTable();
        Dates = rs.getDateByMachineID(machine_id);
        foreach (DataRow r in Dates.Rows)
        {
            string date = r["dateRecorded"].ToString();
            string dateRecorded = date.Trim();
            string dateDisplay = dateRecorded.Substring(0, dateRecorded.IndexOf(" ")).Trim();      
            
            //string dateDisplay = date.Substring(0, 10);
            // string dateName = date.Substring(0, 10);
            System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(dateDisplay, date, true);
            DropDownList1.Items.Add(ls);
        }

    }

    protected void UpdateButton_Click(object sender, EventArgs e)
    {
        Label photoLabel = FormViewMachines.FindControl("photoLabel") as Label;
        if (photoLabel.Text == string.Empty || photoLabel.Text == "" || photoLabel.Text == "&nbsp;" || photoLabel.Text == "Not Available")
        {
            photoLabel.Text = "NotAvailable.jpg";
        }
    }
    protected void FormViewMachines_DataBound(object sender, EventArgs e)
    {
        Label photoLabel = FormViewMachines.FindControl("photoLabel") as Label;
        System.Web.UI.WebControls.Image photoImage = FormViewMachines.FindControl("photoImage") as System.Web.UI.WebControls.Image;
        //setting the Machine Image
        string path = Server.MapPath("../photos/" + photoLabel.Text);

        System.Drawing.Image image = System.Drawing.Image.FromFile(path, true);
        ImageEditor objimg = new ImageEditor();
        int height = 0;
        int width = 0;
        if (objimg.isPortrait(image))
        {
            height = 160;
            width = 120;
        }
        else
        {
            height = 120;
            width = 160;
        }
        photoImage.Attributes.Add("Width", Convert.ToString(width));
        photoImage.Attributes.Add("Height", Convert.ToString(height));
        photoImage.ImageUrl = "../photos/" + photoLabel.Text;

        if (FormViewMachines.CurrentMode == FormViewMode.Edit)
        {
            if (photoLabel.Text != "NotAvailable.JPG")
            {
                Button removeButton = FormViewMachines.FindControl("removeButton") as Button;
                removeButton.Visible = true;
            }
        }
    }
    protected void uploadButton_Click(object sender, EventArgs e)
    {
        Label photoLabel = FormViewMachines.FindControl("photoLabel") as Label;
        FileUpload photoFileUpload = FormViewMachines.FindControl("photoFileUpload") as FileUpload;
        Label statusLabel = FormViewMachines.FindControl("statusLabel") as Label;
        System.Web.UI.WebControls.Image photoImage = FormViewMachines.FindControl("photoImage") as System.Web.UI.WebControls.Image;

        //to retrieve only Filename from the complete path
        int extractPos = photoFileUpload.FileName.LastIndexOf("\\") + 1;
        string photoFileName = photoFileUpload.FileName.Substring(extractPos, photoFileUpload.FileName.Length - extractPos);
        if (photoFileName.IndexOf("/") >= 0 || photoFileName.IndexOf("\\") >= 0)
        {
            //We found a / or \
            Response.End();
        }

        if (photoFileUpload.HasFile)
        {
            //to check file extension is JPG.
            string fileExt = System.IO.Path.GetExtension(photoFileUpload.FileName);
            if (fileExt.ToUpper() == ".JPG")
            {

                //resize image before uploading - start.
                try
                {
                    System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(photoFileUpload.PostedFile.InputStream);
                    int height = 0;
                    int width = 0;
                    // check if image is in potrait or landscape scale.
                    if (objimg.isPortrait(imageToBeResized))
                    {
                        height = 800;
                        width = 600;
                    }
                    else
                    {
                        height = 600;
                        width = 800;
                    }

                    Bitmap bitmap = objimg.ResizeThisImage(width, height, imageToBeResized);
                    //Save uploaded file to server at the in the Pics folder.
                    bitmap.Save(Request.PhysicalApplicationPath
                                    + "photos\\" + photoFileName, ImageFormat.Jpeg);
                    statusLabel.Text = " File Name: " + photoFileUpload.PostedFile.FileName + "<br>" +
                            " File Size: " + photoFileUpload.PostedFile.ContentLength + " kb<br>" +
                            " File Type: " + photoFileUpload.PostedFile.ContentType;
                    photoImage.Visible = true;
                    photoImage.Attributes.Add("Width", Convert.ToString(0.4 * bitmap.Width));
                    photoImage.Attributes.Add("Height", Convert.ToString(0.4 * bitmap.Height));
                    photoImage.ImageUrl = "../photos/" + photoFileName;

                    bitmap.Dispose();
                    imageToBeResized.Dispose();

                    //bind photo file name to textbox.
                    photoLabel.Text = photoFileName;
                    Button removeButton = FormViewMachines.FindControl("removeButton") as Button;
                    removeButton.Visible = true;

                }
                catch (ArgumentException)
                {
                    statusLabel.Text = "Unknown image file!";
                }
                catch (ThreadAbortException)
                {

                }
                catch (Exception ex)
                {
                    statusLabel.Text = "Unknown error: " + ex;
                }
            }
            else
            {
                statusLabel.Text = "Only 'jpeg' files allowed!";
            }
        }
        else
        {
            statusLabel.Text = "You have not specified a file.";
        }
    }
    protected void removeButton_Click(object sender, EventArgs e)
    {
        Label photoLabel = FormViewMachines.FindControl("photoLabel") as Label;
        System.Web.UI.WebControls.Image photoImage = FormViewMachines.FindControl("photoImage") as System.Web.UI.WebControls.Image;
        photoLabel.Text = "Not Available";
        photoImage.Visible = false;
    }
    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
    {


        Session.Contents.Remove("UserDetails");
        Session.Abandon();
        Session.Contents.RemoveAll();
        FormsAuthentication.SignOut();
        Response.Redirect("../Default.aspx");
    }


}
